<template>
  <div class="goods">
    <div class="left" :style="{float: 'left'}">
    <van-sidebar
      v-model="activeKey"
      >
        <van-sidebar-item
        v-for="(item, index) in goods"
        :key="index"
        :title="item.name"
        @click="click" />
      </van-sidebar>
    </div>
    <div v-if="flag">
      <div
      class="right"
      :style="{float: 'left', width: '295px'}"
      v-for="(foods, index) in goods[Index].foods"
      :key="index"
      >
        <van-card
          :title="foods.name"
          :thumb="foods.image"
        >
         <template #desc>
           <p>{{foods.description}}</p>
           <p>月销售{{foods.sellCount}}份 <span :style="{marginLeft:'10px'}">好评率{{foods.rating}}%</span></p>
         </template>
         <template #price>
           <p>
             <span :style="{color: 'red', fontSize:'14px'}">￥{{foods.price}}</span>
             <span
            class="add"
            @click="addToCart({...foods, amount:1})"
            >
              +
             </span>
          </p>
         </template>
        </van-card>
      </div>
    </div>
    <van-goods-action>
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="amount" />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="" />
      <van-goods-action-button type="warning" text="加入购物车" />
      <van-goods-action-button type="danger" text="立即购买" @click="$router.push('/order')" />
    </van-goods-action>
  </div>
</template>

<script>
import { getShopGoods } from '@/api/detial'
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'Goods',
  data () {
    return {
      goods: [],
      activeKey: 0,
      Index: 0,
      flag: false,
      amount: 0
    }
  },
  computed: {
    ...mapState(['cart'])
  },
  async created () {
    const res = await getShopGoods()
    console.log(res.data.data)
    this.goods = res.data.data
    this.getAmount()
  },
  methods: {
    ...mapMutations(['addToCart']),
    click (index) {
      this.Index = index
    },
    getAmount () {
      this.cart.forEach((item) => {
        this.amount += item.amount
        return this.amount
      })
    }
  },
  watch: {
    goods: {
      handler: function (newVal) {
        if (this.goods.length) {
          this.flag = true
        }
      },
      immediate: true
    },
    cart: {
      handler: function (newVal) {
        this.amount++
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
  .goods{
    display: flex;
    height: 100%;
    background: #F7F8FA;
    margin-bottom: 50px;
     .left{
       width: 80px;
       height: 100%;
     }
     .right{
       flex: 1;
     }
  }
.add{
  font-size: 20px;
  margin-left: 120px;
  display: inline-block;
  border: 1px solid;
  text-align: center;
  line-height: 24px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgb(7, 158, 7);
  color: #eee;
}
</style>
